//
//  ST_SKCaptionView.swift
//  ST_ST_SKPhotoBrowser
//
//  Created by suzuki_keishi  on 2015/10/07.
//  Copyright © 2015 suzuki_keishi. All rights reserved.
//

import UIKit

open class ST_SKCaptionView: UIView {
    fileprivate var photo: ST_SKPhotoProtocol?
    fileprivate var photo_label: UILabel!
    fileprivate var photoLabelPadding: CGFloat = 10
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    public convenience init(photo: ST_SKPhotoProtocol) {
        self.init(frame: CGRect(x: 0, y: 0, width: ST_SKMesurement.screenWidth, height: ST_SKMesurement.screenHeight))
        self.photo = photo
        setup()
    }
    
    open override func sizeThatFits(_ size: CGSize) -> CGSize {
        guard let text = photo_label.text, text.count > 0 else {
            return CGSize.zero
        }
        
        let font: UIFont = photo_label.font
        let width: CGFloat = size.width - photoLabelPadding * 2
        let height: CGFloat = photo_label.font.lineHeight * CGFloat(photo_label.numberOfLines)
        
        let attributedText = NSAttributedString(string: text, attributes: [NSAttributedString.Key.font: font])
        let textSize = attributedText.boundingRect(with: CGSize(width: width, height: height), options: .usesLineFragmentOrigin, context: nil).size
        
        return CGSize(width: textSize.width, height: textSize.height + photoLabelPadding * 2)
    }
}

private extension ST_SKCaptionView {
    func setup() {
        isOpaque = false
        autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleRightMargin, .flexibleLeftMargin]
        
        // setup photo_label
        setupPhotoLabel()
    }
    
    func setupPhotoLabel() {
        photo_label = UILabel(frame: CGRect(x: photoLabelPadding, y: 0, width: bounds.size.width - (photoLabelPadding * 2), height: bounds.size.height))
        photo_label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        photo_label.isOpaque = false
        photo_label.backgroundColor = SKCaptionOptions.backgroundColor
        photo_label.textColor = SKCaptionOptions.textColor
        photo_label.textAlignment = SKCaptionOptions.textAlignment
        photo_label.lineBreakMode = SKCaptionOptions.lineBreakMode
        photo_label.numberOfLines = SKCaptionOptions.numberOfLine
        photo_label.font = SKCaptionOptions.font
//        photo_label.shadowColor = UIColor(white: 0.0, alpha: 0.5)
//        photo_label.shadowOffset = CGSize(width: 0.0, height: 1.0)
        photo_label.text = photo?.caption

        addSubview(photo_label)
    }
}

